//
//  QuDanBaseWebController.m
//  QuDanOEM
//
//  Created by xiaohuang on 2021/10/18.
//

#import "QuDanBaseWebController.h"
#import <WebKit/WebKit.h>
@interface QuDanBaseWebController ()
<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UINavigationControllerDelegate,UINavigationBarDelegate>
@property (nonatomic,strong)WKWebView *webView;
@property (nonatomic,strong)UIProgressView *progressView;
@end

@implementation QuDanBaseWebController
-(WKWebView *)webView{
   if (!_webView) {
       WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
       configuration.allowsAirPlayForMediaPlayback = YES;
       configuration.allowsInlineMediaPlayback = YES;
       configuration.processPool = [[WKProcessPool alloc] init];
       WKUserContentController *userContentController = [[WKUserContentController alloc] init];
       [userContentController addScriptMessageHandler:self name:@"NotMap"];
       configuration.suppressesIncrementalRendering = YES;
       configuration.userContentController = userContentController;
       _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, QD_IPHONE_WIDTH,QD_IPHONE_HEIGHT-Height_NavBar) configuration:configuration];
       _webView.backgroundColor = [UIColor whiteColor];
       _webView.navigationDelegate = self;
       _webView.UIDelegate = self;
       [_webView addObserver:self forKeyPath:@"estimatedProgress" options:0 context:nil];
       _webView.allowsBackForwardNavigationGestures = YES;
   }
   return _webView;
}
- (UIProgressView *)progressView{
   if (!_progressView) {
       _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 1);
       // 设置进度条的底彩
       [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
       _progressView.progressTintColor = QD_MainThemColor;
   }
   return _progressView;
}
- (void)viewDidLoad {
   [super viewDidLoad];
   self.view.backgroundColor = [UIColor whiteColor];
   self.navigationItem.title = self.webTitle;
   //添加到主控制器上
   [self.view addSubview:self.webView];
   //添加进度条
   [self.view addSubview:self.progressView];
   [self webViewloadURLType];
}
- (void)dealloc
{
   [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
- (void)webViewloadURLType {
   switch (self.loadType) {
       case WKWebLoadTypeNotSpecifiy:
           return;
           break;
       case WKWebLoadTypeWebURLString:{
           NSURLRequest * Request_zsj = [NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
           [self.webView loadRequest:Request_zsj];
           break;
       }
       case WKWebLoadTypeAuthorizationWebURLString:{
           //创建一个NSMutableURLRequest 的对象
           NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.URLString]];
           NSString * token = @"";
           if (token.length) {
               [request setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];//token
           }
           [self.webView loadRequest:request];
           break;
       }
       case WKWebLoadTypeWebHTMLString:{
           [self loadHostHtml:self.URLString];
           break;
       }
       case WKWebLoadTypeHTMLString:{
           [self.webView loadHTMLString:self.URLString baseURL:[[NSBundle mainBundle] bundleURL]];
           break;
       }
       case WKWebLoadTypePOSTWebURLString:{
           [self loadHostHtml:@"baidu"];
           break;
       }
   }
}
- (void)loadHostHtml:(NSString *)fileName
{
   NSLog(@"self.longitude:%@",self.longitude);
   NSLog(@"self.latitude:%@",self.latitude);
   NSString * pathString = [[NSBundle mainBundle] pathForResource:@"baidu/baidu" ofType:@"htm"];
   NSString * urlString2 = [[NSString stringWithFormat:@"?longitude=%@&latitude=%@",self.longitude,self.latitude]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
   NSLog(@"urlString2:%@",urlString2);
   [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString2 relativeToURL:[NSURL fileURLWithPath:pathString]]]];
//    NSMutableArray *queryItemArray = [NSMutableArray array];
//    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString * path = [paths objectAtIndex:0];
//    path = [path stringByAppendingString:[NSString stringWithFormat:@"/baidu/baidu.html"]];
//    NSURL * url = [NSURL fileURLWithPath:path isDirectory:NO];
//    NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
//    [queryItemArray addObject:[NSURLQueryItem queryItemWithName:@"longitude" value:@"116.391232"]];
//    [queryItemArray addObject:[NSURLQueryItem queryItemWithName:@"latitude" value:@"39.906167"]];
//    [urlComponents setQueryItems:queryItemArray];
//    [self.webView loadFileURL:urlComponents.URL allowingReadAccessToURL:[NSURL fileURLWithPath: [paths objectAtIndex:0]]];
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"baidu/baidu" ofType:@"html"];
//    NSString *urlStr = [NSString stringWithFormat:@"?longitude=%@&latitude=%@",self.longitude,self.latitude];
//    NSLog(@"urlStr:%@",urlStr);
//    //120.047298
//    //29.325966
//
//    //116.391232
//    //39.906167
//    path = [path stringByAppendingString:@"?longitude=120.047298&latitude=29.325966"];
//    path = [@"file://" stringByAppendingString:path];
//    NSURL *url = [NSURL URLWithString:path];
//    NSLog(@"path：%@， url：%@", path, url);
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [self.webView loadRequest:request];
}
- (void)loadWebURLSring:(NSString *)string {
   if ([string hasPrefix:@"http://"] || [string hasPrefix:@"https://"]) {
       string = string;
   }else{
       string = [NSString stringWithFormat:@"http://%@", string];
   }
   self.URLString = string;
   self.loadType = WKWebLoadTypeWebURLString;
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
   NSLog(@"网页由于某些原因加载失败");
}
//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
   if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView) {
       [self.progressView setAlpha:1.0f];
       BOOL animated = self.webView.estimatedProgress > self.progressView.progress;
       [self.progressView setProgress:self.webView.estimatedProgress animated:animated];
       if(self.webView.estimatedProgress >= 1.0f) {
           [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
               [self.progressView setAlpha:0.0f];
           } completion:^(BOOL finished) {
               [self.progressView setProgress:0.0f animated:NO];
           }];
       }
   }else {
       [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
   }
}
#pragma mark ================ WKNavigationDelegate ================
//这个是网页加载完成，导航的变化
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
   //隐藏菊花
   [SVProgressHUD dismiss];
   // 获取加载网页的标题
   if (!_webTitle) {
       self.title = self.webView.title;
   }
   [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (void)backAction:(id)sender {
   //首先看看web能不能后退
   if ([self.webView canGoBack]) {
       [self.webView goBack];
   } else if (self.navigationController.viewControllers.count > 1) {
       //看看native能不能后退
       [self.navigationController popViewControllerAnimated:YES];
   }
}
#pragma mark - WKScriptMessageHandler
//! WKWebView收到ScriptMessage时回调此方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
   NSLog(@"333333");
   if ([message.name caseInsensitiveCompare:@"NotMap"] == NSOrderedSame) {
       NSLog(@"NotMapNotMapNotMap");
       //[WKWebViewWKScriptMessageHandlerController showAlertWithTitle:message.name message:message.body cancelHandler:nil];
   }
}
@end
